#include "widget.h"
#include "ui_widget.h"
#include "packetcapturer.h"
#include "sessiondialog.h"
#include "packetdetaildialog.h"
#include <QMessageBox>
#include <QDateTime>
#include <QScrollBar>
#include <QTableWidgetItem>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_adapterSelector(nullptr)
    , m_packetModel(nullptr)
    , m_totalPackets(0)
    , m_totalBytes(0)
    , m_packetCapturer(nullptr)
    , m_isFiltered(false)
    , m_sessionManager(nullptr)
    , m_sessionModel(nullptr)
    , m_selectedSessionId("")
{
    ui->setupUi(this);
    initUI();
    initMenuBar();
    initPacketTable();
    initSessionTable();
    
    // 设置按钮初始状态
    ui->stopCaptureButton->setEnabled(false);
    
    // 创建会话管理器
    m_sessionManager = new SessionManager(this);
    connect(m_sessionManager, &SessionManager::newSessionDetected, this, &Widget::onNewSessionDetected);
    connect(m_sessionManager, &SessionManager::sessionUpdated, this, &Widget::onSessionUpdated);
    connect(m_sessionManager, &SessionManager::sessionCompleted, this, &Widget::onSessionCompleted);
    
    // 启动会话超时检查
    m_sessionManager->startSessionTimeoutCheck(5000);
    m_sessionManager->setSessionTimeout(30000); // 30秒超时
}

Widget::~Widget()
{
    if (m_packetCapturer) {
        m_packetCapturer->stopCapture();
        delete m_packetCapturer;
        m_packetCapturer = nullptr;
    }
    
    if (m_sessionManager) {
        m_sessionManager->stopSessionTimeoutCheck();
        delete m_sessionManager;
        m_sessionManager = nullptr;
    }
    
    delete m_packetModel;
    delete m_sessionModel;
    delete m_adapterSelector;
    delete ui;
}

void Widget::initUI()
{
    // 设置窗口标题
    setWindowTitle("QTNETSniffer");
    
    // 设置窗口大小
    resize(1000, 800);
}

void Widget::initMenuBar()
{
    // 清除默认菜单栏
    delete ui->menuBar;
    ui->menuBar = nullptr;
    
    // 创建新的菜单栏
    QMenuBar *menuBar = new QMenuBar(this);
    
    // 创建捕获菜单
    QMenu *captureMenu = menuBar->addMenu("捕获");
    
    // 创建开始捕获菜单项
    QAction *startCaptureAction = captureMenu->addAction("开始捕获");
    connect(startCaptureAction, &QAction::triggered, this, &Widget::on_actionStartCapture_triggered);
    
    // 创建停止捕获菜单项
    QAction *stopCaptureAction = captureMenu->addAction("停止捕获");
    connect(stopCaptureAction, &QAction::triggered, this, &Widget::on_actionStopCapture_triggered);
    
    // 创建退出菜单项
    captureMenu->addSeparator();
    QAction *exitAction = captureMenu->addAction("退出");
    connect(exitAction, &QAction::triggered, this, &Widget::on_actionExit_triggered);
    
    // 创建设置菜单
    QMenu *settingsMenu = menuBar->addMenu("设置");
    QAction *settingsAction = settingsMenu->addAction("设置");
    connect(settingsAction, &QAction::triggered, this, &Widget::on_actionSettings_triggered);
    
    // 创建帮助菜单
    QMenu *helpMenu = menuBar->addMenu("帮助");
    QAction *aboutAction = helpMenu->addAction("关于");
    connect(aboutAction, &QAction::triggered, this, &Widget::on_actionAbout_triggered);
    
    // 替换UI中的菜单栏
    ui->verticalLayout_3->insertWidget(0, menuBar);
}

void Widget::initPacketTable()
{
    // 创建表格模型
    m_packetModel = new QStandardItemModel(this);
    
    // 设置表头
    QStringList headers;
    headers << "序号" << "时间" << "源MAC" << "目标MAC" << "源IP" << "目标IP" << "协议" << "长度";
    m_packetModel->setHorizontalHeaderLabels(headers);
    
    // 设置表格
    ui->packetTable->setModel(m_packetModel);
    ui->packetTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->packetTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->packetTable->setSortingEnabled(true);
    
    // 自动调整列宽
    for (int i = 0; i < headers.size(); i++) {
        ui->packetTable->horizontalHeader()->setSectionResizeMode(i, QHeaderView::Interactive);
    }
    
    // 连接点击信号
    connect(ui->packetTable, &QTableView::clicked, this, &Widget::on_packetTable_clicked);
    connect(ui->packetTable, &QTableView::doubleClicked, this, &Widget::on_packetTable_doubleClicked);
    

}

// 初始化会话表格
void Widget::initSessionTable()
{
    // 创建表格模型
    m_sessionModel = new QStandardItemModel(this);
    
    // 设置表头
    QStringList headers;
    headers << "协议类型" << "状态" << "客户端" << "服务器" << "数据包数" << "字节数" << "持续时间" << "摘要";
    m_sessionModel->setHorizontalHeaderLabels(headers);
    
    // 设置表格
    ui->sessionTable->setModel(m_sessionModel);
    ui->sessionTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->sessionTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->sessionTable->setSortingEnabled(true);
    
    // 自动调整列宽
    for (int i = 0; i < headers.size(); i++) {
        ui->sessionTable->horizontalHeader()->setSectionResizeMode(i, QHeaderView::Interactive);
    }
    
    // 连接点击信号
    connect(ui->sessionTable, &QTableView::clicked, this, &Widget::onSessionTableClicked);
}

void Widget::updateStats()
{
    // 更新协议统计表格
    ui->protocolStatsTable->setRowCount(0); // 清空表格
    
    int row = 0;
    for (auto it = m_protocolStats.begin(); it != m_protocolStats.end(); ++it) {
        ui->protocolStatsTable->insertRow(row);
        ui->protocolStatsTable->setItem(row, 0, new QTableWidgetItem(it.key()));
        ui->protocolStatsTable->setItem(row, 1, new QTableWidgetItem(QString::number(it.value())));
        row++;
    }
    
    // 更新总统计信息
    ui->totalPacketsLabel->setText(QString("总数据包数: %1").arg(m_totalPackets));
    ui->totalBytesLabel->setText(QString("总字节数: %1").arg(m_totalBytes));
}

void Widget::addSamplePacket()
{
    // 样例数据包已移除
    // 此函数保留以维持兼容性，但不再添加任何样例数据包
}

void Widget::showAdapterSelector()
{
    if (!m_adapterSelector) {
        m_adapterSelector = new AdapterSelector(this);
        connect(m_adapterSelector, &QDialog::accepted, this, &Widget::onAdapterSelected);
    }
    
    if (m_packetCapturer) {
        // 获取可用网卡列表
        QList<AdapterInfo> adapters = m_packetCapturer->getAvailableAdapters();
        QList<QPair<QString, QString>> adapterPairs;
        for (const auto &adapter : adapters) {
            adapterPairs.append(qMakePair(adapter.name, adapter.description));
        }
        m_adapterSelector->setAvailableAdapters(adapterPairs);
    }
    
    m_adapterSelector->show();
}

void Widget::on_actionStartCapture_triggered()
{
    on_startCaptureButton_clicked();
}

void Widget::on_actionStopCapture_triggered()
{
    on_stopCaptureButton_clicked();
}

void Widget::on_actionExit_triggered()
{
    // 停止捕获
    if (m_packetCapturer && m_packetCapturer->isCapturing()) {
        m_packetCapturer->stopCapture();
    }
    
    // 退出应用
    close();
}

void Widget::on_actionSettings_triggered()
{
    QMessageBox::information(this, "设置", "设置功能尚未实现");
}

void Widget::on_actionAbout_triggered()
{
    QMessageBox::about(this, "关于 QTNETSniffer",
                      "QTNETSniffer 是一个基于Qt的网络数据包捕获工具\n" \
                      "版本: 1.0\n" \
                      "作者: QTNETSniffer 团队\n" \
                      "版权所有 © 2024");
}

void Widget::on_startCaptureButton_clicked()
{
    // 创建或初始化数据包捕获器
    if (!m_packetCapturer) {
        m_packetCapturer = new PacketCapturer(this);
        connect(m_packetCapturer, &PacketCapturer::packetCaptured, this, &Widget::onPacketCaptured);
        connect(m_packetCapturer, &PacketCapturer::captureStarted, this, &Widget::onCaptureStarted);
        connect(m_packetCapturer, &PacketCapturer::captureStopped, this, &Widget::onCaptureStopped);
        connect(m_packetCapturer, &PacketCapturer::captureError, this, &Widget::onCaptureError);
    }
    
    // 显示网卡选择对话框
    showAdapterSelector();
}

void Widget::on_stopCaptureButton_clicked()
{
    if (m_packetCapturer && m_packetCapturer->isCapturing()) {
        m_packetCapturer->stopCapture();
    }
}

void Widget::on_applyFilterButton_clicked()
{
    m_filterExpression = ui->filterLineEdit->text();
    
    if (m_filterExpression.isEmpty()) {
        QMessageBox::warning(this, "过滤", "过滤表达式不能为空");
        return;
    }
    
    // 应用过滤
    m_filteredPackets.clear();
    for (const auto &packet : m_packets) {
        if (applyFilter(packet)) {
            m_filteredPackets.append(packet);
        }
    }
    
    m_isFiltered = true;
    updateFilteredTable();
    
    addLog(QString("应用过滤: %1, 匹配到 %2 个数据包").arg(m_filterExpression).arg(m_filteredPackets.size()));
}

void Widget::on_clearFilterButton_clicked()
{
    ui->filterLineEdit->clear();
    m_filterExpression.clear();
    m_isFiltered = false;
    
    // 重新显示所有数据包
    m_packetModel->clear();
    QStringList headers;
    headers << "序号" << "时间" << "源MAC" << "目标MAC" << "源IP" << "目标IP" << "协议" << "长度";
    m_packetModel->setHorizontalHeaderLabels(headers);
    
    for (const auto &packet : m_packets) {
        QList<QStandardItem *> rowItems;
        rowItems.append(new QStandardItem(QString::number(packet.index)));
        rowItems.append(new QStandardItem(packet.timestamp));
        rowItems.append(new QStandardItem(packet.sourceMac));
        rowItems.append(new QStandardItem(packet.destMac));
        rowItems.append(new QStandardItem(packet.sourceIp));
        rowItems.append(new QStandardItem(packet.destIp));
        rowItems.append(new QStandardItem(packet.protocol));
        rowItems.append(new QStandardItem(QString::number(packet.length)));
        
        m_packetModel->appendRow(rowItems);
    }
    
    addLog("已清除过滤");
}

void Widget::on_packetTable_clicked(const QModelIndex &index)
{
    if (!index.isValid()) {
        return;
    }
    
    int row = index.row();
    
    // 获取选中的数据包
    const PacketInfo *packet = nullptr;
    if (m_isFiltered) {
        if (row >= 0 && row < m_filteredPackets.size()) {
            packet = &m_filteredPackets.at(row);
        }
    } else {
        if (row >= 0 && row < m_packets.size()) {
            packet = &m_packets.at(row);
        }
    }
    
    if (packet) {
        displayPacketDetails(*packet);
    }
}

void Widget::on_packetTable_doubleClicked(const QModelIndex &index)
{
    if (!index.isValid()) {
        return;
    }
    
    int row = index.row();
    
    // 获取选中的数据包
    const PacketInfo *packet = nullptr;
    if (m_isFiltered) {
        if (row >= 0 && row < m_filteredPackets.size()) {
            packet = &m_filteredPackets.at(row);
        }
    } else {
        if (row >= 0 && row < m_packets.size()) {
            packet = &m_packets.at(row);
        }
    }
    
    if (packet) {
        // 显示数据包详情对话框
        PacketDetailDialog *dialog = new PacketDetailDialog(*packet, this);
        dialog->setAttribute(Qt::WA_DeleteOnClose);
        dialog->show();
    }
}

void Widget::onAdapterSelected()
{
    if (m_adapterSelector) {
        // 获取选中的网卡
        m_currentAdapter = m_adapterSelector->getSelectedAdapter();
        
        // 开始捕获
        if (m_packetCapturer) {
            m_packetCapturer->startCapture(m_currentAdapter);
        }
    }
}

void Widget::onPacketCaptured(const PacketInfo &packetInfo)
{
    // 创建一个可修改的副本
    PacketInfo packet = packetInfo;
    
    // 设置正确的序号
    packet.index = m_packets.size() + 1;
    
    // 添加到数据包列表
    m_packets.append(packet);
    
    // 更新统计信息
    m_protocolStats[packet.protocol]++;
    m_totalPackets++;
    m_totalBytes += packet.length;
    
    // 更新UI
    updateStats();
    
    // 将会话传递给会话管理器处理
    if (m_sessionManager) {
        m_sessionManager->processPacket(packet);
    }
    
    // 检查是否应该在表格中显示此数据包
    if (!m_isFiltered || applyFilter(packet)) {
        QList<QStandardItem *> rowItems;
        rowItems.append(new QStandardItem(QString::number(packet.index)));
        rowItems.append(new QStandardItem(packet.timestamp));
        rowItems.append(new QStandardItem(packet.sourceMac));
        rowItems.append(new QStandardItem(packet.destMac));
        rowItems.append(new QStandardItem(packet.sourceIp));
        rowItems.append(new QStandardItem(packet.destIp));
        rowItems.append(new QStandardItem(packet.protocol));
        rowItems.append(new QStandardItem(QString::number(packet.length)));
        
        m_packetModel->appendRow(rowItems);
        
        // 如果正在过滤，更新过滤列表
        if (m_isFiltered && applyFilter(packet)) {
            m_filteredPackets.append(packet);
        }
        
        // 自动滚动到最后一行
        ui->packetTable->scrollToBottom();
    }
}

void Widget::onCaptureStarted()
{
    // 更新按钮状态
    ui->startCaptureButton->setEnabled(false);
    ui->stopCaptureButton->setEnabled(true);
    
    // 添加日志
    addLog(QString("开始捕获数据包，网卡: %1").arg(m_currentAdapter));
}

void Widget::onCaptureStopped()
{
    // 更新按钮状态
    ui->startCaptureButton->setEnabled(true);
    ui->stopCaptureButton->setEnabled(false);
    
    // 添加日志
    addLog("停止捕获数据包");
}

void Widget::onCaptureError(const QString &errorMsg)
{
    // 显示错误消息
    QMessageBox::critical(this, "捕获错误", errorMsg);
    
    // 更新按钮状态
    ui->startCaptureButton->setEnabled(true);
    ui->stopCaptureButton->setEnabled(false);
    
    // 添加日志
    addLog(QString("捕获错误: %1").arg(errorMsg));
}

void Widget::addLog(const QString &message)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->logTextEdit->append(QString("[%1] %2").arg(timestamp).arg(message));
    
    // 自动滚动到最后一行
    QScrollBar *scrollBar = ui->logTextEdit->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
}

// 应用过滤规则
bool Widget::applyFilter(const PacketInfo &packet)
{
    // 改进版过滤逻辑，支持部分匹配、协议名称、源IP、目标IP、MAC地址过滤
    // 支持简单的关键词匹配
    
    QString filter = m_filterExpression.toLower();
    
    // 如果过滤表达式为空，不过滤
    if (filter.isEmpty()) {
        return true;
    }
    
    // 检查协议 - 支持部分匹配
    if (packet.protocol.toLower().contains(filter)) {
        return true;
    }
    
    // 检查IP地址 - 支持部分匹配
    if (packet.sourceIp.toLower().contains(filter) || packet.destIp.toLower().contains(filter)) {
        return true;
    }
    
    // 检查MAC地址 - 支持部分匹配
    if (packet.sourceMac.toLower().contains(filter) || packet.destMac.toLower().contains(filter)) {
        return true;
    }
    
    // 检查端口（从传输层详情中提取）
    QString transportDetail = packet.transportLayerDetail.toLower();
    if (transportDetail.contains(filter)) {
        return true;
    }
    
    // 检查应用层协议（从应用层详情中提取）
    QString appDetail = packet.applicationLayerDetail.toLower();
    if (appDetail.contains(filter)) {
        return true;
    }
    
    return false;
}

void Widget::updateFilteredTable()
{
    // 清空表格
    m_packetModel->clear();
    QStringList headers;
    headers << "序号" << "时间" << "源MAC" << "目标MAC" << "源IP" << "目标IP" << "协议" << "长度";
    m_packetModel->setHorizontalHeaderLabels(headers);
    
    // 重新填充表格
    for (const auto &packet : m_filteredPackets) {
        QList<QStandardItem *> rowItems;
        rowItems.append(new QStandardItem(QString::number(packet.index)));
        rowItems.append(new QStandardItem(packet.timestamp));
        rowItems.append(new QStandardItem(packet.sourceMac));
        rowItems.append(new QStandardItem(packet.destMac));
        rowItems.append(new QStandardItem(packet.sourceIp));
        rowItems.append(new QStandardItem(packet.destIp));
        rowItems.append(new QStandardItem(packet.protocol));
        rowItems.append(new QStandardItem(QString::number(packet.length)));
        
        m_packetModel->appendRow(rowItems);
    }
}

void Widget::displayPacketDetails(const PacketInfo &packet)
{
    QString details;
    
    // 基本信息
    details += "=== 基本信息 ===\n";
    details += QString("序号: %1\n").arg(packet.index);
    details += QString("时间戳: %1\n").arg(packet.timestamp);
    details += QString("长度: %1 字节\n\n").arg(packet.length);
    
    // 以太网信息
    details += "=== 数据链路层 (以太网) ===\n";
    details += packet.linkLayerDetail;
    details += "\n";
    
    // IP信息
    details += "=== 网络层 (IP) ===\n";
    details += packet.networkLayerDetail;
    details += "\n";
    
    // TCP/UDP信息
    details += "=== 传输层 ===\n";
    details += packet.transportLayerDetail;
    details += "\n";
    
    // 应用层信息
    details += "=== 应用层 ===\n";
    details += packet.applicationLayerDetail;
    
    ui->packetDetailInfo->setPlainText(details);
}

// 更新会话表格
void Widget::updateSessionTable()
{
    if (!m_sessionManager) {
        return;
    }
    
    // 保存当前选中的会话ID
    QString selectedId = m_selectedSessionId;
    
    // 清空表格
    m_sessionModel->clear();
    QStringList headers;
    headers << "协议类型" << "状态" << "客户端" << "服务器" << "数据包数" << "字节数" << "持续时间" << "摘要";
    m_sessionModel->setHorizontalHeaderLabels(headers);
    
    // 获取所有会话
    QList<ProtocolSession> sessions = m_sessionManager->getAllSessions();
    
    // 重新填充表格
    int selectedRow = -1;
    for (int i = 0; i < sessions.size(); i++) {
        const ProtocolSession &session = sessions[i];
        
        // 保存选中行的索引
        if (session.id == selectedId) {
            selectedRow = i;
        }
        
        // 获取状态字符串
        QString stateStr;
        switch (session.state) {
        case SessionState::ACTIVE:
            stateStr = "活跃";
            break;
        case SessionState::COMPLETED:
            stateStr = "已完成";
            break;
        case SessionState::ERROR:
            stateStr = "错误";
            break;
        case SessionState::TIMED_OUT:
            stateStr = "超时";
            break;
        }
        
        // 计算持续时间
        QString durationStr;
        qint64 durationMs = session.getDurationMs();
        if (durationMs < 1000) {
            durationStr = QString("%1 ms").arg(durationMs);
        } else {
            durationStr = QString("%1 s").arg(durationMs / 1000.0, 0, 'f', 1);
        }
        
        // 创建表格行
        QList<QStandardItem *> rowItems;
        rowItems.append(new QStandardItem(session.typeString));
        rowItems.append(new QStandardItem(stateStr));
        rowItems.append(new QStandardItem(QString("%1:%2").arg(session.clientAddress).arg(session.clientPort)));
        rowItems.append(new QStandardItem(QString("%1:%2").arg(session.serverAddress).arg(session.serverPort)));
        rowItems.append(new QStandardItem(QString::number(session.packetIndices.size())));
        rowItems.append(new QStandardItem(QString::number(session.totalBytes)));
        rowItems.append(new QStandardItem(durationStr));
        rowItems.append(new QStandardItem(session.summary.isEmpty() ? "无摘要" : session.summary));
        
        // 存储会话ID作为数据
        rowItems[0]->setData(session.id, Qt::UserRole);
        
        // 添加行到表格
        m_sessionModel->appendRow(rowItems);
    }
    
    // 如果之前选中了会话，重新选中它
    if (selectedRow >= 0 && selectedRow < m_sessionModel->rowCount()) {
        ui->sessionTable->selectRow(selectedRow);
        // 不再自动触发点击事件，避免在模态对话框打开时形成无限循环
        // onSessionTableClicked(m_sessionModel->index(selectedRow, 0));
    }
}

// 处理新会话
void Widget::onNewSessionDetected(const ProtocolSession &session)
{
    addLog(QString("检测到新的%1会话: %2:%3 → %4:%5").arg(
        session.typeString, session.clientAddress, QString::number(session.clientPort),
        session.serverAddress, QString::number(session.serverPort)));
    
    // 更新会话表格
    updateSessionTable();
}

// 处理会话更新
void Widget::onSessionUpdated(const ProtocolSession &)
{
    // 更新会话表格
    updateSessionTable();
}

// 处理会话完成
void Widget::onSessionCompleted(const ProtocolSession &session)
{
    addLog(QString("%1会话完成: %2").arg(session.typeString, session.getReadableSummary()));
    
    // 更新会话表格
    updateSessionTable();
}

// 处理会话表格点击
void Widget::onSessionTableClicked(const QModelIndex &index)
{
    if (!index.isValid()) {
        return;
    }
    
    int row = index.row();
    
    // 获取会话ID
    QModelIndex idIndex = m_sessionModel->index(row, 0);
    QString sessionId = idIndex.data(Qt::UserRole).toString();
    
    // 保存选中的会话ID
    m_selectedSessionId = sessionId;
    
    // 获取会话并显示详情
    if (m_sessionManager) {
        ProtocolSession *session = m_sessionManager->getSessionById(sessionId);
        if (session) {
            // 显示会话详情到下方的文本框
            displaySessionDetails(*session);
            
            // 打开新的对话框显示会话详情和相关数据包
            SessionDialog *dialog = new SessionDialog(m_sessionManager, *session, m_packets, this);
            dialog->exec();
            delete dialog;
        }
    }
}

// 显示会话详情
void Widget::displaySessionDetails(const ProtocolSession &session)
{
    QString details;
    
    // 基本信息
    details += "=== 会话基本信息 ===\n";
    details += QString("协议类型: %1\n").arg(session.typeString);
    
    // 获取状态字符串
    QString stateStr;
    switch (session.state) {
    case SessionState::ACTIVE:
        stateStr = "活跃";
        break;
    case SessionState::COMPLETED:
        stateStr = "已完成";
        break;
    case SessionState::ERROR:
        stateStr = "错误";
        break;
    case SessionState::TIMED_OUT:
        stateStr = "超时";
        break;
    }
    
    details += QString("状态: %1\n").arg(stateStr);
    details += QString("开始时间: %1\n").arg(session.startTime.toString("yyyy-MM-dd hh:mm:ss.zzz"));
    
    if (session.endTime.isValid()) {
        details += QString("结束时间: %1\n").arg(session.endTime.toString("yyyy-MM-dd hh:mm:ss.zzz"));
    }
    
    // 计算持续时间
    qint64 durationMs = session.getDurationMs();
    QString durationStr;
    if (durationMs < 1000) {
        durationStr = QString("%1 ms").arg(durationMs);
    } else {
        durationStr = QString("%1 s").arg(durationMs / 1000.0, 0, 'f', 1);
    }
    
    details += QString("持续时间: %1\n").arg(durationStr);
    details += QString("客户端: %1:%2\n").arg(session.clientAddress).arg(session.clientPort);
    details += QString("服务器: %1:%2\n").arg(session.serverAddress).arg(session.serverPort);
    details += QString("数据包数: %1\n").arg(session.packetIndices.size());
    details += QString("总字节数: %1\n").arg(session.totalBytes);
    details += QString("请求次数: %1\n").arg(session.requestCount);
    details += QString("响应次数: %1\n\n").arg(session.responseCount);
    
    // 会话摘要
    if (!session.summary.isEmpty()) {
        details += "=== 会话摘要 ===\n";
        details += session.summary;
        details += "\n\n";
    }
    
    // 协议特定信息
    if (!session.additionalInfo.isEmpty()) {
        details += "=== 协议详情 ===\n";
        
        // 按类型和序号排序显示请求和响应
        QMap<QString, QString> sortedInfo;
        
        // 先添加请求
        for (int i = 1; i <= session.requestCount; i++) {
            QString key = QString("Request%1").arg(i);
            if (session.additionalInfo.contains(key)) {
                sortedInfo[key] = session.additionalInfo[key];
            }
        }
        
        // 再添加响应
        for (int i = 1; i <= session.responseCount; i++) {
            QString key = QString("Response%1").arg(i);
            if (session.additionalInfo.contains(key)) {
                sortedInfo[key] = session.additionalInfo[key];
            }
        }
        
        // 添加命令（FTP等协议）
        for (int i = 1; i <= 100; i++) { // 限制最大命令数
            QString key = QString("Command%1").arg(i);
            if (!session.additionalInfo.contains(key)) {
                break;
            }
            sortedInfo[key] = session.additionalInfo[key];
        }
        
        // 显示排序后的信息
        for (auto it = sortedInfo.constBegin(); it != sortedInfo.constEnd(); ++it) {
            details += QString("%1: %2\n").arg(it.key()).arg(it.value());
        }
    }
    
    // 显示在会话详情文本框中
    ui->sessionDetailInfo->setPlainText(details);
}

// 过滤会话
void Widget::filterSessions(const QString &filterExpression)
{
    // 框架功能，暂未实现
    // 这里简化实现，实际应该根据过滤条件筛选会话
    // 在完整实现中，应该使用类似applyFilter的逻辑来筛选会话
    updateSessionTable();
}
